<template>
    <div>
        <div class="right-wrapper-btnGroup">
            <div>
                <label>筛选区间：</label>
                <el-date-picker
                    v-model="baseData.startTime"
                    type="date"
                    placeholder="开始时间"
                    value-format="yyyy/MM/dd"
                    format="yyyy年MM月dd日"
                    size="small"
                    style="width:160px"
                    >
                </el-date-picker>
                    至
                <el-date-picker
                    v-model="baseData.endTime"
                    type="date"
                    value-format="yyyy/MM/dd"
                    format="yyyy年MM月dd日"
                    placeholder="结束时间"
                    size="small"
                    style="width:160px"
                    >
                </el-date-picker>
                <el-button  size="mini" type="primary" icon="el-icon-search" @keyup. style="margin-left:10px" @keyup.enter.native="getDateQueryList" @click="getDateQueryList">查询</el-button>
            </div>
            <div>
                <el-button  size="mini" type="warning" icon="el-icon-edit-outline" class="btn" @click="filterDialog=true">数据过滤</el-button>
            </div>
        </div>
        <div class="collapse-content" style="margin-top: 10px;">
            <div class="collapse-card"  ref="table-wrapper">
                <div class="collapse-card-header" @click="toggleBox(1)">
                    <div class="collapse-title">
                        <div> <i class="iconfont title-icon">&#xe671;</i>数据展示</div>
                        <div class="describe">
                            <i class="iconfont greenText">&#xe711;</i> 正常
                            <i class="iconfont yellowText">&#xe711;</i> 异常
                            <i class="iconfont redText">&#xe711;</i> 错误
                        </div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠表格" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(1) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-top" ref="table-wrapper" v-loading="tableLoading" element-loading-text="数据加载中，请稍后" element-loading-spinner="el-icon-loading" v-show="isTableExpanded">
                        <div class="table-tips" v-if="showRoleCheck">📝数据审核功能已启用。现支持通过右键点击数据表格中的单元格，唤出操作菜单，执行审核相关操作。</div>
                        <tableView :tableHeight="tableHeight" isEnv :tableList="tableList" @preview="preview" v-if="tableList.length > 0" @updateValue="handleUpdateValue"  :showRoleCheck="showRoleCheck"/>
                    <noData showData v-if="tableList.length == 0" />
                    </div>
                </transition>
            </div>
            <div class="collapse-card"  style="margin-top:10px">
                <div class="collapse-card-header" @click="toggleBox(2)">
                    <div class="collapse-title">
                        <div> <i class="iconfont title-icon">&#xe7a8;</i>过程线展示</div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠图表" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(2) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-bot"  v-show="isChartExpanded" v-loading="chartLoading" element-loading-text="图形加载中，请稍后" element-loading-spinner="el-icon-loading">
                       <noData showChart v-if="chartData == null" description="暂无过程线"/>
                        <chartLine v-show="chartData != null" :chartData="chartData" :field="field" :watchTime="watchTime" height="220px" ref="chartRef"/>
                    </div>
                </transition>
            </div>
        </div>

        <!-- 弹窗部分 -->
        <dataFilter :filterData="filtering" :visible.sync="filterDialog" @filteringSubmit="filteringSubmit"/>
        
    </div> 
</template>
<script>
import {getEnvironmentData,GetValueAllEndCopy,updateValue} from "@/api/https";
import dataFilter from './dataFilter.vue'
import noData from '../../base/noData.vue'
import TableView from './TableView.vue';
import chartLine from '@/components/base/chartLine.vue'
import DateUtils from '@/utils/dateUtils';
export default {
    props:{
        stationId:{
           type:[String,Number],
            default:''
        },
        treeID:{
            type:Number,
            default:0
        },
        showRoleCheck:{
            type:Number,
            default:0
        }
    },
    components:{dataFilter,noData,TableView,chartLine},
    data() {
        return {
            activeNames: [1,2],
            filterDialog:false,
            tableLoading:false,
            chartLoading:false,
            tableList:[],
            tableHeight:'calc(100vh - 600px)',
            baseData: {
                stationID: this.stationId,
                treeID: this.treeID,
                startTime: '',
                endTime: '',
                pageIndex: 1,
                pageSize: 30,
                timeSequence: '倒序',
            },
            filtering:{
                a: true,
                b: true,
                c: true,
                d: true,
                e: true,
                f: true,
                g: false,
                h: true,
                m: true,
                n: true,
                k:false,
                l:false,
                valueType: 6,
            },
            totalPage:1,
            compsLineValues:'',
            chartData:null,
            watchTime:null,
            field:null,
        }
    },
    mounted(){
        this.baseData.startTime = DateUtils.formatDate(DateUtils.getDate('fiveyearsago'))
        this.baseData.endTime = DateUtils.formatDate(DateUtils.getDate('today'))
        this.getTableList();
    },
    deactivated(){
        this.clearChart();
    },
    activated(){
        if(this.chartData){
            this.updateChart()
        }
    },
    beforeDestroy() {
        this.$refs.chartRef?.cleanupChart();
        this.chartData = null;
        this.tableList = [];
    },
    computed: {
        isTableExpanded() {
            return this.activeNames.includes(1);
        },
        isChartExpanded() {
            return this.activeNames.includes(2);
        }
    },
    watch:{
        'stationId':{
            handler(newVal, oldVal) {
                if (newVal && newVal !== oldVal && oldVal != undefined) {
                    this.clearData();
                    this.getTableList();
                }
            },
            immediate: true
        }
    },
    methods: {
        toggleBox(num) {
            const index = this.activeNames.indexOf(num);
            if (index > -1) {
                this.activeNames.splice(index, 1);
            } else {
                this.activeNames.push(num);
            }
            this.adjustTableHeight();
        },
        adjustTableHeight() {
            const hasTable = this.isTableExpanded;
            const hasChart = this.isChartExpanded;
            
            if (hasTable && !hasChart) {
                this.tableHeight = 'calc(100vh - 360px)';
            } else if (!hasTable && hasChart) {
                
            } else {
                this.tableHeight = 'calc(100vh - 600px)';
            }
        },
        clearData(){
            this.tableList = []
            this.tableLoading = false
            this.chartLoading = false
            this.chartData = null
        },
        getTableList() {
            const { h, m, n } = this.filtering;
            let valueType = -1;

            if (h && !m && !n) valueType = 0;
            else if (!h && m && !n) valueType = 1;
            else if (!h && !m && n) valueType = 2;
            else if (h && m && !n) valueType = 3;
            else if (h && !m && n) valueType = 4;
            else if (!h && m && n) valueType = 5;
            else if (h && m && n) valueType = 6;

            this.filtering.valueType = valueType
            this.tableLoading = true
            this.chartLoading = true
            const _data = {...this.baseData,...this.filtering}
            getEnvironmentData(_data).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.filtering = res.data[0].filteringstate
                    this.tableLoading = false
                    this.tableList = [...res.data]
                    this.getChartLineData()
                }else{
                    this.clearData()
                    this.clearChart();
                    this.tableLoading = false
                    this.chartLoading = false
                    this.$message.error(res.errorMessage)
                }
            })
        },

        // 过程线部分
        getChartLineData(){
            GetValueAllEndCopy(this.tableList[0].code_ID,this.tableList[0].compname,this.filtering,this.baseData.startTime,this.baseData.endTime).then(res=>{
                if(res.isSuccess){
                    if (res.data && res.data.valueData != null) {
                      this.chartData = {...res.data}
                      this.watchTime = null
                      this.field = null
                    }else{
                        this.chartData = null
                    }
                    this.chartLoading =false
                }else{
                    this.chartData = null
                    this.chartLoading =false
                    this.$message.error(res.errorMessage)
                }
            })
        },
        preview(row,column) {
            if(column.title == '测值结果'){
                GetValueAllEndCopy(row.code_ID,row.compname,this.filtering,this.baseData.startTime,this.baseData.endTime).then(res =>{
                    if(res.isSuccess && res.data && res.data.valueData){
                        let lineData = res.data.valueData || [];
                        if (lineData.length > 0) {
                            this.chartLoading = true
                            this.chartData = res.data
                            const time = row.watchTime.split(' ')
                            this.watchTime = time[0]
                            this.field = row[column.field]
                            this.$nextTick(()=>{
                                this.updateChart();
                                this.chartLoading =false
                            })
                            
                        }else{
                            this.chartData = null
                            this.chartLoading =false
                        }
                    }else{
                        this.chartData = null
                        this.chartLoading =false
                    }
                });
            }
        },
        getDateQueryList(){
            if (this.baseData.startTime && this.baseData.endTime) {
                const start = new Date(this.baseData.startTime)
                const end = new Date(this.baseData.endTime)
                
                if (end < start) {
                    this.$message.warning('结束时间不能小于开始时间！')
                    return
                }
            }
            this.clearData()
            this.getTableList();
        },
        
        handleUpdateValue(data){
            updateValue(data).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    let err = []
                    let success = []
                    let message = ''
                    res.data.forEach(item=>{
                        if(item.rn){
                            success.push(item.id)
                        }else{
                            err.push(item.mess)
                            message += `<p style="line-height:30px">${item.mess}</p>`
                        }
                    })
                    if(err.length > 0){
                        this.$message({
                            type:'error',
                            dangerouslyUseHTMLString: true,
                            message: message
                        });
                    }
                    if(success.length > 0){
                        this.getDateQueryList()
                    }
                        
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        filteringSubmit(filterData){
            this.filtering = {...filterData}
            this.getDateQueryList()
        },
        clearChart() {
            this.$refs.chartRef?.clearChart();
        },
        
        updateChart() {
           this.$refs.chartRef?.updateChart();
        }
    }
}
</script>
<style scoped lang="scss">
.right-wrapper-btnGroup{
    width: 100%;
    height: 60px;
    background: #fff;
    border-radius:2px;
    padding:12px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

::v-deep .ico{
    font-size: 20px !important;
    vertical-align: middle !important;
}
::v-deep .result{
    i{
        margin-right: 8px;
        font-size: 14px;
    }
}

.describe{
  font-weight: normal;
  margin-left:10px;
  font-size: 12px;
  i{
    font-size: 12px;
  }
}
</style>